<template>
    <div id="information">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>个人中心 </el-breadcrumb-item>
            <el-breadcrumb-item>个人资料</el-breadcrumb-item> </el-breadcrumb
        ><br />

        <i class="iconfont icon-r-paper" style="font-size: 32px">
            <b style="font-size: 28px">完善个人资料</b></i
        >
        <br />
        <br />
        <el-form
            :model="informationForm"
            :rules="rules"
            ref="informationForm"
            label-width="100px"
            class="demo-ruleForm"
            style="margin-left: -100px;"
        >
            <el-row>
                <el-col :span="6">
                    <el-form-item>
                        <el-upload
                            class="avatar-uploader"
                            action="http://localhost:9291/personnel_management/employee/uploadImg"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                        >
                            <img
                                v-if="imageUrl"
                                :src="BaseApi + imageUrl"
                                class="avatar"
                            />
                            <i
                                v-else
                                class="el-icon-plus avatar-uploader-icon"
                            ></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="姓名：" prop="nickName">
                                <el-input v-model="informationForm.nickName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="年龄：">
                                <el-input
                                    type="number"
                                    min="18"
                                    max="70"
                                    v-model="informationForm.age"
                                    disabled
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="性别：">
                                <el-select
                                    style="width: 100%"
                                    v-model="informationForm.sex"
                                    @change="$forceUpdate()"
                                    placeholder="请选择性别"
                                    clearable
                                >
                                    <el-option label="女" value="0"></el-option>
                                    <el-option label="男" value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="身份证号：" prop="idCard">
                                <el-input v-model="informationForm.idCard" @input="handleIdCardChange"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="电话号码：" prop="username">
                                <el-input
                                    maxlength="11"
                                    v-model="informationForm.username"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="住址：">
                                <el-input
                                    type="text"
                                    v-model="informationForm.address"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20">
                            <el-form-item label="所属部门：">
                                <el-select
                                    disabled
                                    style="width: 100%"
                                    v-model="informationForm.deptId"
                                    placeholder="请选择部门"
                                    filterable
                                    @change="$forceUpdate()"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20">
                            <el-form-item label="备注：">
                                <el-input
                                    type="textarea"
                                    cols="50"
                                    rows="3"
                                    v-model="informationForm.info"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button
                    type="primary"
                    @click="submitInformationForm('informationForm')"
                    style="font-size: 18px; transition: all 0.3s;"
                    class="submit-btn"
                >
                    <i class="iconfont icon-r-yes" style="font-size: 18px"></i>
                    提交</el-button
                >
                <el-button
                    @click="resetForm('informationForm')"
                    style="font-size: 18px"
                >
                    <i
                        class="iconfont icon-r-refresh"
                        style="font-size: 18px"
                    ></i>
                    重置</el-button
                >
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { listByQo } from "@/api/personnel_management/department/deptApi";
import { popup } from "@/assets/js/common";
import { queryInformation } from "@/api/personal/personApi";
import { update } from "@/api/personnel_management/employee/empApi";
import { loginEmp } from "@/assets/js/auth";

export default {
    name: 'Information',
    data() {
        // 电话号码校验
        const validatePhone = (rule, value, callback) => {
            const phoneReg = /^1[3-9]\d{9}$/
            if (!value) {
                callback(new Error('请输入电话号码'))
            } else if (!phoneReg.test(value)) {
                callback(new Error('请输入正确的手机号码'))
            } else {
                callback()
            }
        }
        // 身份证号校验
        const validateIdCard = (rule, value, callback) => {
            const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            if (!value) {
                callback(new Error('请输入身份证号'))
            } else if (!idCardReg.test(value)) {
                callback(new Error('请输入正确的身份证号'))
            } else {
                callback()
            }
        }
        // 姓名校验
        const validateName = (rule, value, callback) => {
            const nameReg = /^[\u4e00-\u9fa5]{2,}$/
            if (!value) {
                callback(new Error('请输入姓名'))
            } else if (!nameReg.test(value)) {
                callback(new Error('请输入正确的姓名（至少2个汉字）'))
            } else {
                callback()
            }
        }
        return {
            BaseApi: this.$store.state.BaseApi,
            loginEid: loginEmp().id,
            informationForm: {},
            imageUrl: "",
            options: [],
            rules: {
                username: [
                    { required: true, validator: validatePhone, trigger: 'blur' }
                ],
                nickName: [
                    { required: true, validator: validateName, trigger: 'blur' }
                ],
                idCard: [
                    { required: true, validator: validateIdCard, trigger: 'blur' }
                ]
            },
        };
    },
    methods: {
        deptAll() {
            listByQo({}).then((res) => {
                res = res.data;
                if (res.code == 200) {
                    this.options = res.data;
                } else {
                    popup(res.msg, "error");
                }
            });
        },
        init() {
            queryInformation().then((res) => {
                res = res.data;
                if (res.code == 200) {
                    this.informationForm = { ...res.data };
                    this.imageUrl = this.informationForm.headImg;
                } else {
                    popup(res.msg, "error");
                }
            });
        },
        submitInformationForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    update(this.informationForm).then((res) => {
                        res = res.data;
                        if (res.code == 200) {
                            popup("更新成功，本次修改将在下次登录后生效");
                        } else {
                            popup(res.msg, "error");
                        }
                        this.init();
                    });
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.init();
        },
        /*上传头像*/
        handleAvatarSuccess(res) {
            this.informationForm.headImg = res.url;
            this.imageUrl = res.url;
        },
        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" || file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 3;
            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 3MB!");
            }
            return isJPG && isLt2M;
        },
        // 根据身份证号计算年龄
        calculateAge(idCard) {
            if (!idCard) return
            let birth = ''
            if (idCard.length === 18) {
                birth = idCard.substring(6, 14)
            } else if (idCard.length === 15) {
                birth = '19' + idCard.substring(6, 12)
            }
            if (birth) {
                const year = birth.substring(0, 4)
                const month = birth.substring(4, 6)
                const day = birth.substring(6, 8)
                const birthDate = new Date(year, month - 1, day)
                const today = new Date()
                let age = today.getFullYear() - birthDate.getFullYear()
                const monthDiff = today.getMonth() - birthDate.getMonth()
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--
                }
                this.informationForm.age = age
            }
        },
        // 监听身份证号变化
        handleIdCardChange(value) {
            this.calculateAge(value)
        }
    },
    mounted() {
        this.imageUrl = "";
        this.deptAll();
        this.init();
    },
};
</script>

<style scoped>
.submit-btn:hover {
    background-color: #67c23a !important;
    color: white !important;
    border-color: #67c23a !important;
}
</style>
